package com.lsw.joy.login.controller;

import com.lsw.joy.login.service.RegisterService;
import com.lsw.joy.utils.ResultMsg;
import com.lsw.joy.utils.ResultStatusCode;
import io.swagger.annotations.Api;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author Hasee
 * @date 2021/10/14
 */
@Controller
@RequestMapping("/public/register")
@Api(tags = {"用户注册接口"})
public class RegisterController {

    @Resource
    private RegisterService registerService;

    @PostMapping("/toRegister")
    @ResponseBody
    public ResultMsg toRegister(@RequestParam("userName") String userName,
                                @RequestParam("password") String password){
        //判断用户名是否已存在
        Integer userNameCount = registerService.selectCountByName(userName);
        if (userNameCount > 0){
            return new ResultMsg(ResultStatusCode.USERNAME_EXIST.getResultCode(), ResultStatusCode.USERNAME_EXIST.getResultMessage());
        }
        String newPass = getNewPass("MD5",password,userName,1024);
        //保存用户信息
        registerService.saveUserInformation(userName,newPass);
        return new ResultMsg(ResultStatusCode.SUCCEED.getResultCode(), ResultStatusCode.SUCCEED.getResultMessage());
    }

    public String getNewPass(String algorithmName,String source,String salt ,int hashIterations){
        Object  object = new SimpleHash(algorithmName,source,salt,hashIterations);
        return object.toString();
    }
}
